package com.boot.controller;

import com.boot.entity.Major;
import com.boot.entity.School;
import com.boot.repository.MajorRepository;
import com.boot.repository.SchoolRepository;
import com.boot.vo.BaseMessage;
import com.boot.vo.MessageHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.transaction.Transactional;
import java.util.List;

@RestController
@CrossOrigin(origins = "*")

@RequestMapping("/school")
public class SchoolController {
    @Autowired
    private SchoolRepository schoolRepository;

    @Autowired
    private MajorRepository majorRepository;

    @GetMapping("schoolList")
    public BaseMessage<?> schoolList(String keyword) {
        List<School> all = schoolRepository.findAllBySchoolNameLike(keyword);
        return MessageHandler.createSuccessVo(all, "success");
    }

     // 添加学院
    @RequestMapping("addSchool")
    public BaseMessage<?> addSchool(School school) {
        Boolean b = schoolRepository.existsBySchoolId(school.getSchoolId());
        if (b == true)
            return MessageHandler.createFailedVo("该院系已存在，不可重复添加！");
        if(StringUtils.isBlank(school.getSchoolName()) || StringUtils.isBlank(school.getSchoolId().toString()))
            return MessageHandler.createFailedVo("院系id或名称不为空");
        school.setTeaNum(0);school.setStuNum(0);
        schoolRepository.save(school);
        return MessageHandler.createSuccessVo(school,"院系添加成功");

    }

    @Transactional
    @DeleteMapping("delSchool/{id}")
    public BaseMessage<String> del(@PathVariable Integer id) {
        Boolean b=schoolRepository.existsBySchoolId(id);
        if(b==false)
            return MessageHandler.createFailedVo("该学院不存在");
        School school = schoolRepository.getById(id);
        schoolRepository.deleteBySchoolId(id);
        Boolean a=majorRepository.existsBySchoolId(id);
        if(a==true)
            return MessageHandler.createFailedVo("该学院下属有专业，需先删除相应专业");

        else {
            majorRepository.deleteBySchoolId(id);
            return MessageHandler.createSuccessVo("操作成功");
        }
    }


     // 编辑学院(学院id不可以修改，要修改自己删掉重新添加；可以修改名字/人数)
    @RequestMapping("editSchool")
    @ResponseBody
    public BaseMessage<?> editSchool (School school){
        Boolean b =schoolRepository.existsBySchoolId(school.getSchoolId());
        if(b==false)
            return MessageHandler.createFailedVo("学院id不存在");
        else {
            schoolRepository.save(school);
            return MessageHandler.createSuccessVo("学院编辑成功");
        }
    }

}
